<?php
/**
 * Created by PhpStorm.
 * User: syzhou
 * Date: 2020-11-12
 * Time: 14:06
 */

require_once __DIR__ . '/common.php';

/**
 * @var PDO
 */
global $srcPDO;

/**
 * @var PDO
 */
global $dstPDO;

global $uploadedFilePathsSavePath;
$uploadedFilePaths = file($uploadedFilePathsSavePath, FILE_IGNORE_NEW_LINES);
$srcTable = 'uploaded_files';
$dstTable = $srcTable;

$fetchedSrcTableFields = ['id', 'filename', 'extension', 'path', 'created_at', 'updated_at',];
$fetchedSrcTableFieldsStr = implode(', ', $fetchedSrcTableFields);
$selectSrcRecordsStmt = $srcPDO->prepare("select $fetchedSrcTableFieldsStr from $srcTable where path = ?");
$insertedDstTableFields = $fetchedSrcTableFields;
$insertedDstTableFieldsStr = implode(', ', $insertedDstTableFields);
$insertedDstTableValuePlaceholders = array_map(function($fieldName) {
    return ":$fieldName";
}, $insertedDstTableFields);
$insertedDstTableValuePlaceholdersStr = implode(', ', $insertedDstTableValuePlaceholders);
$insertDstRecordsStmt = $dstPDO->prepare("insert into $dstTable ($insertedDstTableFieldsStr) values ($insertedDstTableValuePlaceholdersStr)");

$i = 1;
foreach ( $uploadedFilePaths as $uploadedFilePath) {
    $selectSrcRecordsStmt->execute([$uploadedFilePath]);
    $srcRecord = $selectSrcRecordsStmt->fetch(PDO::FETCH_ASSOC);
    $selectSrcRecordsStmt->closeCursor();

    $srcRecordId = $srcRecord['id'];
    echo "$i. transfer uploaded_file #$srcRecordId...";
    $i++;
    $dstRecord = $srcRecord;
    $values = [];
    foreach ($insertedDstTableFields as $field) {
        $valuePlaceholder = ":$field";
        $values[$valuePlaceholder] = $dstRecord[$field];
    }
    $insertDstRecordsStmt->execute($values);
}
